package com.yunhai.recipe.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yunhai.common.dto.GlobalException;
import com.yunhai.common.dto.PaginationVo;
import com.yunhai.common.utils.ObjectUtil;
import com.yunhai.common.utils.ReflectionCopy;
import com.yunhai.model.entity.FmsFormulaRuleEntity;
import com.yunhai.model.entity.fms.*;
import com.yunhai.model.entity.fms.FmsFormulaRuleVo;
import com.yunhai.model.vo.fms.FmsFormulaManageQuery;
import com.yunhai.model.vo.fms.FmsFormulaManageVo;
import com.yunhai.model.vo.fms.FmsFormulaSpecVo;
import com.yunhai.model.vo.fms.FmsFormulaStepVo;
import com.yunhai.recipe.mapper.*;
import com.yunhai.recipe.service.FmsFormulaManageService;
import io.swagger.annotations.ApiModelProperty;
import org.apache.commons.beanutils.PropertyUtils;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class FmsFormulaManageServiceImpl implements FmsFormulaManageService {

    @Resource
    private FmsFormulaManageMapper fmsFormulaManageMapper;

    @Resource
    private FmsCodeDictMapper fmsCodeDictMapper;

    @Resource
    private FmsRecipeCategoryMapper fmsRecipeCategoryMapper;

    @Resource
    private FmsFormulaStepMapper fmsFormulaStepMapper;

    @Resource
    private FmsFormulaSpecMapper fmsFormulaSpecMapper;

    @Resource
    private FormulaRuleMapper formulaRuleMapper;

    @Resource
    private FmsMaterialConfigMapper fmsMaterialConfigMapper;

    @Autowired
    private ApplicationContext applicationContext;


    /**
     * 获取 FmsFormulaManage 分页列表
     */
    @Transactional
    public IPage getFmsFormulaManagePagination(PaginationVo paginationVo, FmsFormulaManageQuery fmsFormulaManageQuery ) throws Exception {

        IPage page = new Page( paginationVo.getPageIndex(), paginationVo.getPageSize() );
        LambdaQueryWrapper<FmsFormulaManageEntity> lqs = new LambdaQueryWrapper();
        lqs.eq(fmsFormulaManageQuery.getEnabled() != null,
                FmsFormulaManageEntity::getEnabled,
                fmsFormulaManageQuery.getEnabled());
        lqs.eq(fmsFormulaManageQuery.getCategoryId()!=null,
                FmsFormulaManageEntity::getCategoryId,
                fmsFormulaManageQuery.getCategoryId()
                );
        lqs.likeRight(fmsFormulaManageQuery.getName()!=null,
                FmsFormulaManageEntity::getName,
                fmsFormulaManageQuery.getName()
        );
        lqs.likeRight(fmsFormulaManageQuery.getNumber()!=null,
                FmsFormulaManageEntity::getNumber,
                fmsFormulaManageQuery.getNumber()
        );

        lqs.orderByDesc( FmsFormulaManageEntity::getCreateTime );
        fmsFormulaManageMapper.selectPage(page, lqs);

        List<FmsFormulaManageEntity> record = page.getRecords();
        if( !ObjectUtil.isNotEmptyList(record)){
            return page;
        }

        /**
         * 获取分类
         * */
        Set<Long> categoryIds = record.stream().map(item->item.getCategoryId()).collect(Collectors.toSet());
        if( ObjectUtil.isNotEmptyList(categoryIds)){
            List<FmsRecipeCategoryEntity> categorys = fmsRecipeCategoryMapper.selectBatchIds(categoryIds);
            if( ObjectUtil.isNotEmptyList(categorys)){
                for( FmsFormulaManageEntity item : record ){
                    categorys.stream().filter(row->row.getId().equals(item.getCategoryId())).findFirst().ifPresent( row->{
                        item.setCategoryName(row.getName());
                    } );
                }
            }
        }

        /**
         * 获取步骤数据
         * */
        Set<Long> productIds = record.stream().map(item->item.getId()).collect(Collectors.toSet());
        LambdaQueryWrapper<FmsFormulaStepEntity> stepLqs = new LambdaQueryWrapper<>();
        stepLqs.in( FmsFormulaStepEntity::getProductId, productIds );
        List<FmsFormulaStepEntity> stepList = fmsFormulaStepMapper.selectList(stepLqs);
        if( ObjectUtil.isNotEmptyList(stepList)){
            for( FmsFormulaManageEntity item : record ){
               List<FmsFormulaStepEntity> filterStepList = stepList.stream().filter(row->row.getProductId().equals(item.getId())).collect(Collectors.toList());
                item.getProductSteps().addAll(filterStepList);
            }
        }
//        productSpecGroups
        /**
         * 获取 spec group 数据。
         * */
        LambdaQueryWrapper<FmsFormulaSpecEntity> specLqs = new LambdaQueryWrapper<>();
        specLqs.in( FmsFormulaSpecEntity::getProductId, productIds );
        List<FmsFormulaSpecEntity> specList = fmsFormulaSpecMapper.selectList(specLqs);
        if(  ObjectUtil.isNotEmptyList(specList) ){
            for( FmsFormulaManageEntity item : record ) {
                List<FmsFormulaSpecEntity> filterSpecList = specList.stream().filter(row->row.getProductId().equals(item.getId())).collect(Collectors.toList());
                List<FmsFormulaSpecEntity> firstRosSpecs = filterSpecList.stream().filter( row->row.getParentId() == 0 ).collect(Collectors.toList());
                List<FmsFormulaSpecEntity> secondsRosSpecs = filterSpecList.stream().filter( row->row.getParentId() != 0 ).collect(Collectors.toList());
                firstRosSpecs.stream().forEach(row->{
                    row.setSpecList(secondsRosSpecs.stream().filter( subRow->{
                        return subRow.getParentId().equals(row.getId());
                    }).collect(Collectors.toList()));
                });
                item.getProductSpecGroups().addAll(firstRosSpecs);
            }
        };


        //获取 productRules
        LambdaQueryWrapper<FmsFormulaRuleEntity> ruleLqs = new LambdaQueryWrapper<>();
        ruleLqs.in( FmsFormulaRuleEntity::getProductId, productIds );
        List<FmsFormulaRuleEntity> ruleList = formulaRuleMapper.selectList(ruleLqs);
        if(  ObjectUtil.isNotEmptyList(ruleList) ){
            for( FmsFormulaManageEntity item : record ) {
                List<FmsFormulaRuleEntity> filterRuleList = ruleList.stream().filter(row->row.getProductId().equals(item.getId())).collect(Collectors.toList());
                item.getProductRules().addAll(filterRuleList);
            }
        };

        Set<Long> materialIds = ruleList.stream().map(item->item.getMaterialId()).collect(Collectors.toSet());
        List<FmsMaterialConfigEntity> materialList = fmsMaterialConfigMapper.selectBatchIds(materialIds);
        if(  ObjectUtil.isNotEmptyList(materialList) ){
            for( FmsFormulaRuleEntity item : ruleList ) {
                materialList.stream().filter(row->row.getId().equals(item.getMaterialId())).findFirst().ifPresent(row->{
                    item.setMaterialName(row.getName());
                });
            }
        };

        return page;
    }


    /**
     * 获取 FmsFormulaManage 所有数据
     *
    */
    @Transactional
    public List<FmsFormulaManageEntity> getFmsFormulaManageAllList( FmsFormulaManageQuery fmsFormulaManageQuery ) throws Exception {

        LambdaQueryWrapper<FmsFormulaManageEntity> lqs = new LambdaQueryWrapper();
        List<FmsFormulaManageEntity> list = fmsFormulaManageMapper.selectList(lqs);
        return list;
    }


    /**
     * 获取 FmsFormulaManage 详情
    */
    @Transactional
    public FmsFormulaManageEntity getFmsFormulaManageDetail( Long id) throws Exception {

        FmsFormulaManageEntity fmsFormulaManage = fmsFormulaManageMapper.selectById(id);
        return fmsFormulaManage;
    }


    /**
     * 新增 FmsFormulaManage
     * */
    @Transactional
    public void addFmsFormulaManage(FmsFormulaManageVo fmsFormulaManageVo) throws Exception {

        FmsFormulaManageEntity fmsFormulaManage = new FmsFormulaManageEntity();
        ReflectionCopy.copyProperties( fmsFormulaManage, fmsFormulaManageVo );
        fmsFormulaManageMapper.insert(fmsFormulaManage);

        FmsCodeDictEntity fmsCodeDictEntity = new FmsCodeDictEntity();
        fmsCodeDictEntity.setId(401L);
        fmsCodeDictEntity.setLastCode(fmsFormulaManageVo.getNumber());
        fmsCodeDictMapper.updateById(fmsCodeDictEntity);

        FmsFormulaManageServiceImpl proxy =  applicationContext.getBean(FmsFormulaManageServiceImpl.class);
        proxy.handsFormulaStep(fmsFormulaManageVo, fmsFormulaManage.getId() );
        proxy.handsFormulaSpecGroups(fmsFormulaManageVo, fmsFormulaManage.getId());
        proxy.handsFormulaRule(fmsFormulaManageVo, fmsFormulaManage.getId());
        return;
    }


    @Transactional
    public void handsFormulaRule( FmsFormulaManageVo fmsFormulaManageVo, Long productId  ) throws Exception {
        LambdaQueryWrapper<FmsFormulaRuleEntity> lqs = new LambdaQueryWrapper<>();
        lqs.eq(FmsFormulaRuleEntity::getProductId, productId);
        formulaRuleMapper.delete(lqs);

        List<FmsFormulaRuleVo> productRules = fmsFormulaManageVo.getProductRules();
        if( !ObjectUtil.isNotEmptyList(productRules) ){
            return;
        }

        for( FmsFormulaRuleVo item : productRules  ){
            FmsFormulaRuleEntity fmsFormulaRuleEntity = new FmsFormulaRuleEntity();
            ReflectionCopy.copyProperties(fmsFormulaRuleEntity, item);
            fmsFormulaRuleEntity.setProductId(productId);
            formulaRuleMapper.insert(fmsFormulaRuleEntity);
        }
    }
    @Transactional
    public void handsFormulaStep( FmsFormulaManageVo fmsFormulaManageVo, Long productId ) throws Exception {
        /***
         * 处理 步骤
         * (1) 先删除
         * (2) 再添加
         */
        List<FmsFormulaStepVo> productSteps = fmsFormulaManageVo.getProductSteps();
        if( !ObjectUtil.isNotEmptyList(productSteps) ){
            return;
        }
        //清除掉之前的。
        LambdaQueryWrapper<FmsFormulaStepEntity> deleteLqs = new LambdaQueryWrapper<>();
        deleteLqs.eq( FmsFormulaStepEntity::getProductId, productId);
        fmsFormulaStepMapper.delete( deleteLqs );
        //增加新的
        for( FmsFormulaStepVo item : productSteps ){
            FmsFormulaStepEntity fmsFormulaStepEntity = new FmsFormulaStepEntity();
            ReflectionCopy.copyProperties(fmsFormulaStepEntity, item);
            fmsFormulaStepEntity.setProductId(productId);
            fmsFormulaStepEntity.setId(null);
            fmsFormulaStepMapper.insert(fmsFormulaStepEntity);
        }
    }
    @Transactional
    public void handsFormulaSpecGroups( FmsFormulaManageVo fmsFormulaManageVo, Long productId  ) throws Exception {

        //获取 spec 列表
        List<FmsFormulaSpecVo> productSpecGroups = fmsFormulaManageVo.getProductSpecGroups();
        if( !ObjectUtil.isNotEmptyList(productSpecGroups) ){
            return;
        }

        LambdaQueryWrapper<FmsFormulaSpecEntity> deleteLqs = new LambdaQueryWrapper<>();
        deleteLqs.eq( FmsFormulaSpecEntity::getProductId, productId );
        fmsFormulaSpecMapper.delete(deleteLqs);

        for( FmsFormulaSpecVo item : productSpecGroups ){
            FmsFormulaSpecEntity entity = new FmsFormulaSpecEntity();
            ReflectionCopy.copyProperties(entity, item);
            entity.setProductId(productId);
            entity.setId(null);
            fmsFormulaSpecMapper.insert(entity);

            Long parentId = entity.getId();

            List<FmsFormulaSpecVo> subList =  item.getSpecList();
            for( FmsFormulaSpecVo subitem: subList ){
                FmsFormulaSpecEntity subItemEntity = new FmsFormulaSpecEntity();
                ReflectionCopy.copyProperties(subItemEntity, subitem);
                subItemEntity.setProductId(productId);
                subItemEntity.setParentId(parentId);
                subItemEntity.setId(null);
                fmsFormulaSpecMapper.insert(subItemEntity);
            }
        }


    }

    /**
     * 更新 FmsFormulaManage
     * */
    @Transactional
    public void updateFmsFormulaManage( FmsFormulaManageVo fmsFormulaManageVo) throws Exception {

        if( fmsFormulaManageVo.getId() == null ){
            throw GlobalException.gen(10021, "id不存在");
        }
        FmsFormulaManageEntity fmsFormulaManage = new FmsFormulaManageEntity();
        ReflectionCopy.copyProperties( fmsFormulaManage, fmsFormulaManageVo );
        fmsFormulaManageMapper.updateById(fmsFormulaManage);

        FmsFormulaManageServiceImpl proxy =  applicationContext.getBean(FmsFormulaManageServiceImpl.class);
        proxy.handsFormulaStep(fmsFormulaManageVo, fmsFormulaManageVo.getId() );
        proxy.handsFormulaSpecGroups(fmsFormulaManageVo, fmsFormulaManageVo.getId());
        proxy.handsFormulaRule(fmsFormulaManageVo, fmsFormulaManageVo.getId());
        return;
    }

    /**
     * 删除 FmsFormulaManage
     * */
    @Transactional
    public void batchRemoveFmsFormulaManage( List<Long> ids ) throws Exception {


        if( !ObjectUtil.isNotEmptyList(ids) ){
            throw GlobalException.gen(10011, "要删除的id不存在");
        }
        fmsFormulaManageMapper.deleteBatchIds(ids);
    }

}

      